package com.tianfeng.fenghuotoutiao.ui.activity.AppListActibity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.liys.doubleclicklibrary.ViewDoubleHelper;
import com.tianfeng.fenghuotoutiao.R;
import com.tianfeng.fenghuotoutiao.model.bean.UserBean;
import com.tianfeng.fenghuotoutiao.ui.activity.base.BaseActivity;
import com.tianfeng.fenghuotoutiao.utils.UIUtils;
import com.zhxu.library.download.DownInfo;
import com.zhxu.library.download.HttpDownManager;
import com.zhxu.library.listener.HttpDownOnNextListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AppDetailActivity extends BaseActivity {

    @BindView(R.id.imageView19)
    ImageView imageView19;
    @BindView(R.id.iv_photo)
    ImageView iv_photo;

    @BindView(R.id.et_appid)
    EditText et_appid;
    @BindView(R.id.et_zhifubaoacc)
    EditText et_zhifubaoacc;
    @BindView(R.id.et_username)
    EditText et_username;

    @BindView(R.id.ll_commit)
    LinearLayout  ll_commit;
    @BindView(R.id.ll_status)
    LinearLayout  ll_status;



    @BindView(R.id.tv_name)
    TextView tv_name;

    @BindView(R.id.tv_commit)
    TextView tv_commit;

    @BindView(R.id.tv_yuanyin)
    TextView tv_yuanyin;

    @BindView(R.id.tv_desc)
    TextView tv_desc;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_down)
    TextView tv_down;

    @BindView(R.id.tv_status)
    TextView tv_status;
    @BindView(R.id.tv_renwudesc)
    TextView tv_renwudesc;
    AppListModel.DataBean dataBean;
    List<IsShowApp.DataBean> isshowList=new ArrayList<>();
    @Override
    public int getContentLayout() {
        return R.layout.activity_app_detail;
    }

    @Override
    protected void initView(View rootView, Bundle savedInstanceState) {
        dataBean= (AppListModel.DataBean) getIntent().getSerializableExtra("app");
        Glide.with(AppDetailActivity.this).load(dataBean.getAppphoto()).into(iv_photo);
        tv_name.setText(dataBean.getAppname());
        tv_money.setText("奖励RMB "+dataBean.getAppmoney());
        tv_renwudesc.setText(dataBean.getApprenwudesc());
        tv_desc.setText(dataBean.getAppdesc());
        ViewDoubleHelper.hookResView(R.id.tv_down, 5000);
        ViewDoubleHelper.hookResView(R.id.tv_commit, 5000);
        ll_commit.setVisibility(View.GONE);
        ll_status.setVisibility(View.GONE);
        requestGetAppList();
        imageView19.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                download(dataBean.getAppurl());
            }
        });
        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(et_appid.getText().toString().trim()) ||TextUtils.isEmpty(et_zhifubaoacc.getText().toString().trim()) ||TextUtils.isEmpty(et_username.getText().toString().trim())){
                    UIUtils.toast(AppDetailActivity.this, "对不起，您输入的内容不能为空");
                } else{
                    UserBean userBean=new UserBean();
                    requestGetAppList(getUserBean().getUserid(),et_appid.getText().toString().trim()
                            ,et_zhifubaoacc.getText().toString().trim()
                            ,et_username.getText().toString().trim()
                            ,dataBean.getAppname(),dataBean.getAppmoney());
                }
            }
        });
    }
    /**
     * 下载的地址
     *
     * @param url
     */
    public void download(String url) {

        //下载的地址；
        final String storeUrl = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/renrentoutiao" + "/renrentoutiao.apk";

        //这里我们对是否有这个文件进行一个校验的操作；

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("下载进度");
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.show();

        DownInfo downInfo = new DownInfo(url, new HttpDownOnNextListener() {

            boolean isSuccess = false;

            @Override
            public void onNext(Object o) {
                isSuccess = true;
            }


            @Override
            public void onStart() {

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                isSuccess = false;
                //这里显示弹窗下载失败；
            }

            @Override
            public void onComplete() {
                UIUtils.toast(AppDetailActivity.this, "下载完成");


                //跳转到安装的界面；
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Uri data = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //这里的话，我们在7.0是需要使用FileProvider;
                    data = FileProvider.getUriForFile(AppDetailActivity.this, "com.tianfeng.fenghuotoutiao.fileprovider", new File(storeUrl));
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(new File(storeUrl));
                }

                intent.setDataAndType(data,
                        "application/vnd.android.package-archive");
                startActivity(intent);
            }

            @Override
            public void updateProgress(long readLength, long countLength) {

                //System.out.println("progress: "+readLength+" total:"+countLength);
                int curProgress = ((int) readLength);
                int totalProgress = ((int) countLength);

                progressDialog.setProgress(curProgress);
                progressDialog.setMax(totalProgress);
            }
        });
        downInfo.setSavePath(storeUrl);
        HttpDownManager.getInstance().startDown(downInfo);
    }
    /**
     * 提交这个人的下载游戏的信息
     */
    public void requestGetAppList(String uid,String appid,String acc,String accname,String appname,String appmoney){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url(String.format("http://tianze1688.com/api/index.php/news/user/getapp?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7" +
                        "&uid="+uid+"&appid="+appid+"&acc="+acc+"&accname="+accname+"&appname="+appname+"&appmoney="+appmoney))
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("TAG", "onResponse: "+response.body().string());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AppDetailActivity.this, "提交体现游戏体验成功，请留意支付宝到账信息\"", Toast.LENGTH_SHORT).show();

                        finish();
                    }
                });

            }
        });
    }


    /**
     * 请求请求是否下载过
     *
     */
    public void requestGetAppList(){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url(String.format("http://tianze1688.com/api/index.php/news/user/getAppuserstatus?osversion=7.1.2&sign=d78fd1c819662088eb9f699fd266dd6d&versionCode=18&adCode=18&from_uid=5&timesc=1557217128587&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=7"+"&from_uid="+getUserBean().getUserid()))
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (TextUtils.isEmpty(result)) return;
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    String data=jsonObject.optString("data");
                    Gson gso=new Gson();




                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            List<IsShowApp.DataBean> applist = gso.fromJson(data, new TypeToken<List<IsShowApp.DataBean>>() {
                            }.getType());
                            isshowList.addAll(applist);
                            if (isshowList.size() > 0) {
                                switch (isshowList.get(0).getStatus()){
                                    case 0:
                                        ll_commit.setVisibility(View.VISIBLE);
                                        ll_status.setVisibility(View.GONE);

                                        break;
                                    case 1:
                                        ll_commit.setVisibility(View.GONE);
                                        ll_status.setVisibility(View.VISIBLE);
                                        tv_status.setText("排队中");
                                        break;
                                    case 2:
                                        ll_commit.setVisibility(View.GONE);
                                        ll_status.setVisibility(View.VISIBLE);
                                        tv_status.setText("提现成功");
                                        break;
                                    case 3:
                                        ll_commit.setVisibility(View.GONE);
                                        ll_status.setVisibility(View.VISIBLE);
                                        tv_status.setText("拒绝提现");
                                        if (TextUtils.isEmpty(isshowList.get(0).getYuanyin())){
                                            return;
                                        }else{
                                            tv_yuanyin.setText(isshowList.get(0).getYuanyin());
                                        }
                                        break;
                                }



                            }else{
                                ll_commit.setVisibility(View.VISIBLE);
                                ll_status.setVisibility(View.GONE);
                                tv_status.setText("审核中");
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
